<?php

namespace app\admin\controller\customer;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Customer extends Backend
{
    
    /**
     * Customer模型对象
     * @var \app\common\model\customer\Customer
     */
    protected $model = null;
    protected $areas = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\customer\Customer;
        $this->_areas = Db::name('area')->where(array('pid'=>0))->select();
        $this->assign('areas',$this->_areas);
        $this->assignconfig('areas',$this->_areas);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
//                    ->with(['area'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
//                    ->with(['area'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as $row) {
                
//                $row->getRelation('area')->visible(['shortname']);
            }
            $list = collection($list)->toArray();
//            foreach ($list as $k=>$v){
//                $list[$k]['area_id'] = $v['area']['shortname'];
//            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function detail($ids = null){
        $row = $this->model->find($ids);

        $list =  Db::name('analysis')->where(array('status'=>array('in',[1,2]),'settle_name'=>$row['company']))->select();


        $symoney = 0;
        foreach ($list as $v){
            if($v['status'] == 1){//待处理
                $symoney+=$v['cost'];
            }else{
                $ymoney = Db::name('analysis_log')->where(array('analysis_id'=>$v['id'],'status'=>1))->sum('price');
                $symoney+=bcsub($v['cost'],$ymoney,2);
            }
        }
        $row['symoney'] = $symoney;
        return $row;
    }
    public function import()
    {
        $filelink = request()->file('file');
        $info = $filelink->move(ROOT_PATH.'/public/'.DS.'uploads/fujian');
        //获取文件名
        $file = ROOT_PATH.'public'.DS.'uploads/fujian'.DS.$info->getsaveName();
        /* 转码 */
        $file = iconv("utf-8", "gb2312", $file);

        if (empty($file) OR !file_exists($file)) {
            throw new \Exception('文件不存在!');
        }

        /** @var Xlsx $objRead */
        $objRead = IOFactory::createReader('Xlsx');

        if (!$objRead->canRead($file)) {
            /** @var Xls $objRead */
            $objRead = IOFactory::createReader('Xls');

            if (!$objRead->canRead($file)) {
                throw new \Exception('只支持导入Excel文件！');
            }
        }

        /* 如果不需要获取特殊操作，则只读内容，可以大幅度提升读取Excel效率 */
        empty($options) && $objRead->setReadDataOnly(true);
        /* 建立excel对象 */
        $obj = $objRead->load($file);
        /* 获取指定的sheet表 */
        $currSheet = $obj->getSheet(0)->toArray();
        for ($i =0;$i<15;$i++){
            unset($currSheet[$i]);
        }

        foreach ($currSheet as $v){
            $area = explode("\\",$v['12']);
            @$pro = $area[2].'省';
            @$area_id = $pro.'/'.$area[3];
            $data[] = array(
                'company'=>$v[2],
                'nickname'=>$v[2],
                'address'=>$v[3],
//                'email'=>$v[1],
                'contacts'=>$v[4],
                'mobile'=>$v[5],
                'bank_account'=>$v[9],
                'bank_name'=>$v[8],
                'bank_of_deposit'=>$v[10],
                'tax_number'=>$v[6],
                'zip_code'=>$v[11],
                'remark'=>$v[7],
                'area_id'=>$area_id,
            );
        }
        $this->model->saveAll($data);
    }

    public function change($ids){
        $row = $this->model->find($ids);
        if($row){
            if($row['is_inside'] == 1){
                $data = array(
                    'is_inside'=>0,
                );
            }else{
                $data = array(
                    'is_inside'=>1,
                );
            }
            $res = $this->model->save($data,array('id'=>$ids));
            if($res){
                $this->success('设置成功');
            }
        }
        $this->error('异常');
    }
}
